package itsm.isperp.module.controller.customer;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.paging.RenderPager;
import itsm.isperp.framework.web.request.DefaultCountQuery;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-24
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("customer/help/user")
public class CusHelpUserController {

  @Autowired
  AppUserService appUserService;

  @Autowired
  IcdIncidentService icdIncidentService;
  @Autowired
  JdbcTemplate jdbcTemplate;

  @RequestMapping(value = { "" })
  public ModelAndView userCenter(HttpServletRequest req) {

    AppUser user = (AppUser) ContextHolder.getLoginUser();
    ModelAndView mv = new ModelAndView();

    mv.addObject("default2", "default");
    if (user == null) {
      mv.setViewName("redirect:/main/login");
    } else {

      mv.addObject("user", user);
      CusCustomerService cusCustomerService = ContextHolder
          .getSpringBean("cusCustomerService");
      CusCustomer customer = cusCustomerService.findOne(user.getCustomerId());
      if (customer != null) {
        mv.addObject("customerName", customer.getFullname());
      }

      DefaultCountQuery cq = new DefaultCountQuery("icd_incident");
      String userName = user.getUsername();

      String myFilter = " cus_user_id='"
          + user.getId()
          + "'"
          + " and process_id IN (SELECT DISTINCT  PROC_INST_ID_ FROM (SELECT  task.PROC_INST_ID_ FROM ACT_RU_TASK task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' AND task.ASSIGNEE_ = '"
          + userName
          + "'  UNION ALL "
          + " SELECT  task.PROC_INST_ID_  FROM act_ru_identitylink task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' "
          + "     AND task.USER_ID_ = '" + userName
          + "' AND task.type_ = 'candidate') task)";
      String myFilter2 = " cus_user_id='"
          + user.getId()
          + "'"
          + " and process_id NOT IN (SELECT DISTINCT  PROC_INST_ID_ FROM (SELECT  task.PROC_INST_ID_ FROM ACT_RU_TASK task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' AND task.ASSIGNEE_ = '"
          + userName
          + "'  UNION ALL "
          + " SELECT  task.PROC_INST_ID_  FROM act_ru_identitylink task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' "
          + "     AND task.USER_ID_ = '" + userName
          + "' AND task.type_ = 'candidate') task)";
      cq.addCountFilter("myTodoIncident", " STATUS<>'已关闭' AND " + myFilter);
      cq.addCountFilter("myDoingIncident", " STATUS<>'已关闭' AND " + myFilter2);
      /*
       * if (itsm.isperp.framework.data.dialect.DialectFactory.getDatabaseType()
       * == DatabaseType.ORACLE) { cq.addCountFilter( "myTocloseIncidentCount",
       * "  are_feedback =0 AND  solver_submit_time IS NOT NULL AND (trunc(sysdate)-trunc(create_date))<30 AND "
       * + myFilter); } else { cq.addCountFilter( "myTocloseIncidentCount",
       * "  are_feedback =0 AND  solver_submit_time IS NOT NULL AND (TO_DAYS(NOW())-TO_DAYS(create_date))<30 AND "
       * + myFilter); }
       */

      cq.addCountFilter("myAllIncidentCount", " STATUS='已关闭' AND cus_user_id='"
          + user.getId() + "'");

      Map<String, Long> taskCount = getTaskCount();
      mv.addObject("taskCount", taskCount);

      /*
       * List<Long> t = cq.getCountResult();
       * 
       * long myTodoIncident = t.get(0), myDoingIncident = t.get(1),
       * myAllIncidentCount = t .get(2);
       * 
       * mv.addObject("myTodoIncident", myTodoIncident);
       * mv.addObject("myDoingIncidentCount", myDoingIncident);
       * mv.addObject("myAllIncidentCount", myAllIncidentCount);
       */
      mv.setViewName("customer/help/user/userCenter");

    }
    return mv;
  }

  public Map<String, Long> getTaskCount() {
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    DefaultCountQuery cq = new DefaultCountQuery("icd_incident");
    String userName = user.getUsername();

    String myFilter = " cus_user_id='"
        + user.getId()
        + "'"
        + " and process_id IN (SELECT DISTINCT  PROC_INST_ID_ FROM (SELECT  task.PROC_INST_ID_ FROM ACT_RU_TASK task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' AND task.ASSIGNEE_ = '"
        + userName
        + "'  UNION ALL "
        + " SELECT  task.PROC_INST_ID_  FROM act_ru_identitylink task  WHERE task.proc_def_id_ LIKE 'incidentProcess%' "
        + "     AND task.USER_ID_ = '" + userName
        + "' AND task.type_ = 'candidate') task) and status in('退回','重新提交')";
    String myFilter2 = " cus_user_id='" + user.getId() + "' ";
    cq.addCountFilter("myTodoIncident", " STATUS<>'已关闭' AND " + myFilter);
    cq.addCountFilter("myDoingIncident", " STATUS<>'已关闭' AND " + myFilter2);
    /*
     * if (itsm.isperp.framework.data.dialect.DialectFactory.getDatabaseType()
     * == DatabaseType.ORACLE) { cq.addCountFilter( "myTocloseIncidentCount",
     * "  are_feedback =0 AND  solver_submit_time IS NOT NULL AND (trunc(sysdate)-trunc(create_date))<30 AND "
     * + myFilter); } else { cq.addCountFilter( "myTocloseIncidentCount",
     * "  are_feedback =0 AND  solver_submit_time IS NOT NULL AND (TO_DAYS(NOW())-TO_DAYS(create_date))<30 AND "
     * + myFilter); }
     */

    cq.addCountFilter("myAllIncidentCount", " STATUS='已关闭' AND cus_user_id='"
        + user.getId() + "'");

    List<Long> t = cq.getCountResult();

    long myTodoIncident = t.get(0), myDoingIncident = t.get(1), myAllIncidentCount = t
        .get(2);
    Map<String, Long> countMap = new HashMap<String, Long>();
    countMap.put("myTodoIncidentCount", myTodoIncident);
    countMap.put("myDoingIncidentCount", myDoingIncident);
    countMap.put("myAllIncidentCount", myAllIncidentCount);
    return countMap;

  }

  /**
   * 我代办任务
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */

  @RequestMapping(value = { "myTodoTask" })
  public ModelAndView myTodoTask(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();

    mv.addObject("default2", "default");
    mv.addObject("myTodoTask", "current");

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    JqGridRequest request = new JqGridRequest();

    request.setSort("create_date", Direction.DESC);

    List<Map<String, Object>> tasks = bpmProcessRunService.getAllTodoList(
        ContextHolder.getLoginUsername(), request);

    mv.addObject("tasks", tasks);

    mv.setViewName("customer/help/user/myTodoTask");
    return mv;
  }

  /**
   * 我的已办任务
   * 
   * @param req
   * @param redirectAttributes
   * @return
   */

  @RequestMapping(value = { "myTodoneTask" })
  public ModelAndView myTodoneTask(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) req.getSession().getAttribute("cusUserLogin");
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }

    mv.addObject("default2", "default");
    mv.addObject("myTodoneTask", "current");

    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");

    String pageIndex = req.getParameter("page");
    int currentPage = 1;
    if (StringUtils.isNotEmpty(pageIndex)) {
      currentPage = Integer.parseInt(pageIndex);
    }

    JqGridRequest request = new JqGridRequest();
    request.isPageable(true);
    request.setRows(15);

    request.setPage(currentPage);

    request.setSort("create_date", Direction.DESC);

    DataResponse<Map<String, Object>> tasks = bpmProcessRunService
        .getAllTodoneList(user.getUsername(), request);

    mv.addObject(
        "pager",
        RenderPager.renderHtml(req, currentPage, tasks.getSize(),
            (int) tasks.getTotalElements()));

    mv.addObject("tasks", tasks);

    mv.setViewName("customer/help/user/myTodoneTask");
    return mv;

  }

  @RequestMapping(value = { "myRequest" })
  public ModelAndView myRequest(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) req.getSession().getAttribute("cusUserLogin");
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }

    mv.addObject("default2", "default");
    mv.addObject("myRequest", "current");

    String pageIndex = req.getParameter("page");
    int currentPage = 1;
    if (StringUtils.isNotEmpty(pageIndex)) {
      currentPage = Integer.parseInt(pageIndex);
    }

    JqGridRequest request = new JqGridRequest();
    request.isPageable(true);
    request.setRows(15);

    request.setPage(currentPage);

    request.addFilterRule("name", JqGridFilterRuleOp.eq, user.getUsername());
    request.setSort("create_date", Direction.DESC);

    mv.setViewName("customer/help/user/myRequest");
    return mv;
  }

  @RequestMapping(value = { "myRequestClose" })
  public ModelAndView myRequestClose(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) req.getSession().getAttribute("cusUserLogin");
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }

    mv.addObject("default2", "default");
    mv.addObject("myRequestClose", "current");

    String pageIndex = req.getParameter("page");
    int currentPage = 0;
    if (StringUtils.isNotEmpty(pageIndex)) {
      currentPage = Integer.parseInt(pageIndex);
    }

    JqGridRequest request = new JqGridRequest();
    request.isPageable(true);
    request.setRows(15);
    request.addFilterRule("account_id", JqGridFilterRuleOp.eq,
        user.getUsername());
    request.addFilterRule("status", JqGridFilterRuleOp.eq, "已关闭");
    request.setSort("create_date", Direction.DESC);

    mv.setViewName("customer/help/user/myRequestClose");
    return mv;
  }

  /**
   * 单点登录到ad域
   * 
   * @param req
   */
  public static void ssoLdap(HttpServletRequest req) {

    String adPasswordCheck = ContextHolder.getConfigByKey("adPasswordCheck");
    if ("1".equals(adPasswordCheck)) {
      AppUser user = (AppUser) req.getSession().getAttribute("cusUserLogin");

      if (user == null) {

        // 当前系统登录的域用户
        // String account = System.getProperty("user.name");
        //
        // Map<String, String> map = System.getenv();
        // String userName = map.get("USERNAME");// 获取用户名
        // String computerName = map.get("COMPUTERNAME");// 获取计算机名
        // String userDomain = map.get("USERDOMAIN");// 获取计算机域名

        Cookie[] cookies = req.getCookies();

        String adUsername = null;
        String adDomain = null;

        for (Cookie co : cookies) {
          if ("adDomain".equals(co.getName())) {
            adDomain = co.getValue();
          }

          if ("adUsername".equals(co.getName())) {
            adUsername = co.getValue();
          }

        }

        if (adUsername != null) {
          if (adUsername.contains("@")) {
            adUsername = adUsername.split("@")[0];
          }

          AppUserService appUserService2 = ContextHolder
              .getSpringBean("appUserService");
          JqGridRequest request = new JqGridRequest();
          request.setRows(1);
          request.isPageable(false);
          if (adUsername.contains("@")) {
            request.addFilterRule("account_id", JqGridFilterRuleOp.eq,
                adUsername);
          } else {
            request.addFilterRule("account_id", JqGridFilterRuleOp.eq,
                adUsername + "@" + adDomain);
          }
          List<AppUser> us = appUserService2.findAll(request);
          if (us != null && us.size() > 0) {
            req.getSession().setAttribute("cusUserLogin", us.get(0));
          }

        }
      }
    }

  }

  // ~~~~~~~~~~~~~~~~修改个人信息

  @RequestMapping("changePersonalInfo")
  public ModelAndView changePersonalInfo(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }
    mv.setViewName("customer/help/user/changePersonalInfo");
    String sql = "select * from cus_user_address where user_name='"
        + user.getUsername() + "'";
    List<Map<String, Object>> addressList = jdbcTemplate.queryForList(sql);
    mv.addObject("addressList", addressList);
    mv.addObject("model", user);
    return mv;

  }

  @RequestMapping("userAddressEdit")
  public ModelAndView userAddressEdit(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    String id = req.getParameter("id");
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }
    if (!StringUtils.isEmpty(id)) {
      String sql = "SELECT * FROM cus_user_address where id='" + id + "'";
      List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
      if (list.size() > 0) {
        mv.addObject("addressModel", list.get(0));
      }

    }
    mv.setViewName("customer/help/user/userAddressEdit");
    mv.addObject("model", user);
    return mv;

  }

  @RequestMapping("changePersonalInfoSave")
  public ModelAndView changePersonalInfoSave(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    try {

      AppUser user = (AppUser) ContextHolder.getLoginUser();
      if (user == null) {
        mv.setViewName("redirect:/customer/help/user/login");
        redirectAttributes.addAttribute("error", "用户未登录");
        return mv;
      }
      // user.setDepartment(req.getParameter("department"));
      user.setEmail(req.getParameter("email"));
      user.setTitle(req.getParameter("title"));
      user.setMobile(req.getParameter("mobile"));
      user.setDegree(req.getParameter("degree"));
      user.setSpeciality(req.getParameter("speciality"));
      // user.setLinkaddress(req.getParameter("linkaddress"));
      // user.setMemo(req.getParameter("memo"));
      // user.setQq(req.getParameter("qq"));
      user.setTel(req.getParameter("tel"));
      user.setPassword(req.getParameter("password"));
      appUserService.saveOrUpdate(user);

      mv.setViewName("customer/help/user/changePersonalInfo");
      mv.addObject("model", user);
      mv.addObject("result", ResultMessage.newInstance(true, "个人信息更新成功！"));

    } catch (Exception e) {
      mv.addObject("result",
          ResultMessage.newInstance(false, "个人信息更新失败，请稍候再试！"));
    }
    return mv;

  }

  // ~~~~~~~~~~~~~~~~修改密码

  @RequestMapping("changePassword")
  public ModelAndView changePassword(HttpServletRequest req,
      RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user/login");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }

    mv.setViewName("customer/help/user/changePassword");
    mv.addObject("user", user);

    return mv;

  }

  @RequestMapping("changePasswordSave")
  public ModelAndView changePasswordSave(HttpServletRequest req,
      RedirectAttributes redirectAttributes) throws Exception {
    ModelAndView mv = new ModelAndView();
    AppUser user = (AppUser) ContextHolder.getLoginUser();
    if (user == null) {
      mv.setViewName("redirect:/customer/help/user");
      redirectAttributes.addAttribute("error", "用户未登录");
      return mv;
    }

    String password = req.getParameter("oldPassword");

    mv.setViewName("customer/help/user/changePassword");
    mv.addObject("user", user);

    String newPassword = req.getParameter("newPassword1");

    ResultMessage r = appUserService
        .changePassword(user, password, newPassword);
    mv.addObject("result", r);
    return mv;

  }

  @RequestMapping("deleteUserAddress")
  @ResponseBody
  public void deleteUserAddress(String id) {
    String sql = "delete from cus_user_address where id=?";
    jdbcTemplate.update(sql, id);
  }

  @RequestMapping("userAddressSave")
  public ModelAndView userAddressSave(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView();
    String userName = ContextHolder.getLoginUsername();
    String address = req.getParameter("address");
    String mobile = "";
    String are_df = req.getParameter("are_df");
    String id = req.getParameter("id");
    if (are_df.equals("1")) {
      String sql0 = "update cus_user_address set are_df=0 where user_name=?";
      jdbcTemplate.update(sql0, userName);
    }
    if (StringUtils.isEmpty(id)) {
      id = HibernateUUIDGenerator.generate();
      String sql = "insert into cus_user_address(id,address,mobile,user_name,are_df) values(uuid(),?,?,?,?)";
      jdbcTemplate.update(sql, address, mobile, userName, are_df);
    }else
    {
      String sql01="delete from cus_user_address where id='"+id+"'";
      jdbcTemplate.update(sql01);
      String sql = "insert into cus_user_address(id,address,mobile,user_name,are_df) values('"+id+"',?,?,?,?)";
      jdbcTemplate.update(sql, address, mobile, userName, are_df);
    }

    mv.setViewName("redirect:/customer/help/user/changePersonalInfo");
    return mv;
  }
}
